package com.open.center.jpa.converter;


import jakarta.persistence.AttributeConverter;

import com.open.center.common.constant.Enumerator;
import com.open.center.common.exception.OpenException;

/**
 * JPA 表字段与实体类属性之间的枚举转换
 *
 * @param <E> 枚举类型
 * @param <V> 枚举属性的值
 */
public abstract class DbEnumConverter<E extends Enum<?> & Enumerator<? extends Enum<?>, V>, V> implements AttributeConverter<E, V> {

    private final Class<E> clazz;

    protected DbEnumConverter(Class<E> clazz) {
        this.clazz = clazz;
    }

    @Override
    public V convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            throw new OpenException("Enum (attribute) is null");
        }
        return attribute.getId();
    }

    @Override
    public E convertToEntityAttribute(V dbData) {

        for (E e : clazz.getEnumConstants()) {
            if (e.getId().equals(dbData)) {
                return e;
            }
        }
        throw new OpenException("Unknown enum " + clazz.getSimpleName() + ", id = " + dbData);
    }
}
